var jdbc = require('../db/jdbc.js');
var widgets = require('../db/widgets.js');

var chai = require('chai');
var should = chai.should();
var assert = chai.assert;

var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);

var sinon = require('sinon');
var Q = require('q');

describe('--数据查询', function() {


    describe('--获取数据库数据 - 正确查询', function() {

        var stub;

        function jdbcPromise() {
            return Q.fcall(function() {
                return [{
                    widgetId: 10
                }];
            });
        };

        beforeEach(function() {
			//console.log();
			console.log('--利用sinon虚拟数据库查询语句类，设置sql查询语句\n');
            stub = sinon.stub(jdbc, "query");
            stub.withArgs('select * from t_widget A left join t_widget_config B on A.id = B.widgetId where userId =? order by x,y', [5120152534]).returns(jdbcPromise());

        });

        it('--利用sql语句，判断获取的数据是否与真实数据一样，用户ID为5120152534', function() {
            return widgets.getWidgets(5120152534).should.eventually.be.an('array');
        });

        afterEach('--恢复数据库',function() {
			//console.log();
			console.log('--恢复数据库');
            stub.restore();
        });
    });
	describe('--获取数据库数据 - 错误查询', function() {

        var stub;

        function jdbcPromise() {
            return Q.fcall(function() {
                throw new Error("widgets error");
            });
        };

        beforeEach(function() {
			//console.log();
			console.log('--利用sinon虚拟数据库查询语句类，设置sql查询语句');
            stub= sinon.stub(jdbc, "query");
            stub.withArgs('select * from t_widget A left join t_widget_config B on A.id = B.widgetId where userId =? order by x,y', [5120152534]).returns(jdbcPromise());

        });

        it('--利用sql语句，判断获取的数据是否与真实数据一样，用户ID为5120152534',function() {
            return widgets.getWidgets(5120152534).should.be.rejectedWith('widgets error');
        });

        afterEach(function() {
			//console.log();
			console.log('--恢复数据库');
            stub.restore();
        });
    });
});